package com.emin.platform.subjectcenter;

import com.emin.platform.subjectcenter.interceptor.RequestLoggerInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication(scanBasePackages = {"com.emin"})
@EnableEurekaClient
@EnableWebMvc
@EnableAsync
@EnableSwagger2
@EntityScan(basePackages = {"com.emin.platform.subjectcenter.entity"})
@EnableDiscoveryClient
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClass = false)
@EnableFeignClients
@Order(value = 1)
public class SubjectcenterApplication extends WebMvcConfigurerAdapter implements
        TransactionManagementConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(SubjectcenterApplication.class, args);
    }

    // Hibernate事物
    @Bean
    public HibernateTransactionManager txManager() {
        HibernateTransactionManager txm = new HibernateTransactionManager(sessionFactory()
                .getObject());
        return txm;
    }

    // Hibernate sessionFactory
    @Bean(name = {"sessionFactory"})
    public HibernateJpaSessionFactoryBean sessionFactory() {
        return new HibernateJpaSessionFactoryBean();
    }

    // 事物管理
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager();
    }

    // SWAGGER配置-------------------------Start
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.emin.platform.subjectcenter.api"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Subjectcenter RESTful APIs")
                .description("主体中心 REST API 文档")
                .termsOfServiceUrl("http://www.emindg.com/")
                .contact(new springfox.documentation.service.Contact("Jack", "", "jack" +
                        ".chen@emindg.com"))
                .version("1.0")
                .build();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    // SWAGGER配置-------------------------End


    @Bean
    public MappingJackson2HttpMessageConverter jacksonHttpMessageConverter() {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        supportedMediaTypes.add(MediaType.TEXT_HTML);
        supportedMediaTypes.add(MediaType.MULTIPART_FORM_DATA);
        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportedMediaTypes.add(MediaType.ALL);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        return converter;
    }

    /**
     * 附件Multipart解决方案
     *
     * @return
     */
/*    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver bean = new CommonsMultipartResolver();
        bean.setDefaultEncoding("utf-8");
        bean.setMaxUploadSize(10 * 1024 * 1024);// 10M
        return bean;
    }*/

    // 拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
/*        registry.addInterceptor(new RequestLoggerInterceptor()).addPathPatterns("/**");
        registry.addInterceptor(new LoggerInterceptorHandler()).addPathPatterns("/**");*/
        super.addInterceptors(registry);
    }

}
